package com.example.smartmedicalsystem.service;

import com.example.smartmedicalsystem.entity.Medicine;
import com.example.smartmedicalsystem.entity.User;
import com.example.smartmedicalsystem.entity.UserMedicine;
import com.example.smartmedicalsystem.repository.MedicineRepository;
import com.example.smartmedicalsystem.repository.UserMedicineRepository;
import com.example.smartmedicalsystem.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserMedicineService {
    private final UserMedicineRepository userMedicineRepository;
    private final MedicineService medicineService;
    private final UserRepository userRepository;
    private final MedicineRepository medicineRepository;

    @Transactional
    public UserMedicine addMedicineToUser(Long userId, Long medicineId, int quantity) {
        medicineService.deductStock(medicineId, quantity);
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Medicine medicine = medicineRepository.findById(medicineId)
                .orElseThrow(() -> new RuntimeException("药品不存在"));
        UserMedicine userMedicine = userMedicineRepository
                .findByUser_IdAndMedicine_Id(userId, medicineId)
                .orElse(new UserMedicine());
        if (userMedicine.getId() == null) {
            userMedicine.setUser(user);
            userMedicine.setMedicine(medicine);
            userMedicine.setQuantity(quantity);
        } else {
            userMedicine.setQuantity(userMedicine.getQuantity() + quantity);
        }
        return userMedicineRepository.save(userMedicine);
    }

    public List<UserMedicine> getUserMedicines(Long userId) {
        return userMedicineRepository.findByUser_Id(userId);
    }
}